'use strict';

const fs = require('fs');

//1、找出所有的路由文件
function findControllerFiles(path) {
    path = path || './controllers';
    let files = fs.readdirSync(path);
    return files.filter(item => {
        return item !== 'index.js';
    })
}

//2、注册所有的路由
function registrRouter(files, router) {
    files.forEach(item => {
        let tmpModule = require('../controllers/' + item.replace('.js', ''));
        // console.log(tmpModule);
        for (let key in tmpModule) {
            let tmpArr = key.split(' ');

            let method = tmpArr[0];// 方法
            let url = tmpArr[1];// 请求地址
            let fn = tmpModule[key];// 请求对应的处理函数

            if (method === 'get') {
                router.get(url, fn);
            } else if (method === 'post') {
                router.post(url, fn);
            } else if (method === 'put') {
                router.put(url, fn);
            } else if (method === 'delete') {
                router.delete(url, fn);
            }
        }
    })
}

module.exports = {
    findControllerFiles,
    registrRouter
}